<template>
	<view class="page-wrap">
		<uni-nav-bar left-icon="left" fixed statusBar title="导航栏组件">
			<view slot="right" class="language-change">
				<text @click="changeLanguage">{{nextLang==='EN' ? '中文' : 'EN'}}</text>
			</view>
		</uni-nav-bar>
		<!-- <view v-if="showLabel" class="label-list out-label">
			<view @click="addClass" class="label-item">
				新增
			</view>
			<view class="label-item" @click="selectAll">
				全选/全不选
			</view>
			<view class="label-item" @click="selectNo">
				反选
			</view>
		</view> -->
		<view class="main-page">
			<view class="content">
				<swiper autoplay interval=1000 circular class="swiper-wrap">
					<swiper-item>
						<img class="swiper-image" src="https://img95.699pic.com/photo/50042/4589.jpg_wh300.jpg"
							mode="" />
					</swiper-item>
					<swiper-item>
						<img class="swiper-image" src="https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF"
							mode="" />
					</swiper-item>
					<swiper-item>
						<img class="swiper-image" src="https://t7.baidu.com/it/u=737555197,308540855&fm=193&f=GIF"
							alt="">
					</swiper-item>
				</swiper>
				<view class="label-list">
					<view @click="addClass" class="label-item">
						新增
					</view>
					<view class="label-item" @click="selectAll">
						全选/全不选
					</view>
					<view class="label-item" @click="selectNo">
						反选
					</view>
				</view>
				<view class="class-list">
					<view class="class-item" v-for="item in classList" :key="item._id">
						<view class="class-con" @click="doSelect(item)">
							<view class="is-select">
								<icon v-show="item.isSelected" color="#FD7135" type="success"></icon>
							</view>
							<view class="class-main">
								<view class="title-row" @click.stop="goDetail(item)">
									<view class="class-label">{{item.label}}</view>
									<view class="class-title">{{item.title}}</view>
								</view>
								<view class="classs-description">
									{{item.description}}
								</view>
								<view class="teacher-list">
									<view class="teacher-item" v-for="teacherItem in item.teacthers"
										:key="teacherItem.id">
										<image class="teacher-icon" :src="teacherItem.userIcon"></image>
										<view class="teacher-info">
											<view class="teacher-name">{{teacherItem.userName}}</view>
											<view class="teacher-role">{{teacherItem.role}}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="class-info">
							<view class="play-btn">
								<view class="delete-btn" @click="deleteClass(item)">删除</view>
								<view class="count">
									<uni-icons type="plus" @click="addNum(item)"></uni-icons>
									<text v-if="item.num>0">{{item.num}}</text>
									<uni-icons type="minus" v-if="item.num>0" @click="deleteNum(item)"></uni-icons>
								</view>
							</view>
							<view class="class-price">
								￥{{item.price}}
							</view>
						</view>
						<!-- view class="class-price">
							￥{{item.price}}
						</view> -->
						<view v-if="item.isPayed" class="is-payed">
							{{languageIndex.purchased}}
						</view>
					</view>
				</view>
			</view>
			<view class="do-assign">
				<view class="price-num">
					<text class="sub-price">￥{{subPrice}}</text><text class="preferential"
						v-if="preferentialNum">{{languageIndex.preferential}}{{preferentialNum}}{{languageIndex.yuan}}</text>
				</view>
				<view :class="[canSubmit?'submit-btn':'disabled']" @click="doSumit">{{languageIndex['这里是提交按钮']}}
				</view>
			</view>
			<uni-pay ref="pay"></uni-pay>
		</view>
	</view>

</template>

<script>
	import {
		// debounce
		throttle
	} from '@/utils/utils.js'
	export default {
		data() {
			return {
				preferentialNum: 0,
				classList: [],
				showLabel: false,
				total_fee: 1, // 支付金额，单位分 100 = 1元
				order_no: "", // 业务系统订单号（即你自己业务系统的订单表的订单号）
				out_trade_no: "", // 插件支付单号
				description: "测试订单", // 支付描述
				type: "test", // 支付回调类型 如 recharge 代表余额充值 goods 代表商品订单（可自定义，任意英文单词都可以，只要你在 uni-pay-co/notify/目录下创建对应的 xxx.js文件进行编写对应的回调逻辑即可）
				custom: {
					a: "a",
					b: 1
				}
			}
		},
		onPullDownRefresh() {
			console.log('下拉加载')
			
		},
		// onPageScroll(e) { //nvue暂不支持滚动监听，可用bindingx代替
		// 	console.log(e.scrollTop)
		// 	if(e.scrollTop>=237) {
		// 		this.showLabel = true
		// 	} else {
		// 		this.showLabel = false
		// 	}
		// },

		onLoad() {
			// uni.hideTabBar()
			//获取课程数据的接口
			// uni.startPullDownRefresh(); //手动调用api方式触发下拉
			this.getClassList()
			this.getPreferentialNum()
		},
		computed: {
			languageIndex() {
				return this.$t('index')
			},
			subPrice() {
				let subNum = 0
				this.classList.map(item => {
					if (item.isSelected) {
						subNum += item.price
					}
				})
				if (subNum <= this.preferentialNum) {
					subNum = 0
					return subNum
				}
				return subNum <= this.preferentialNum ? 0 : subNum - this.preferentialNum
			},
			canSubmit() {
				return this.classList.some(item => item.isSelected)
			},
			nextLang() {
				return this.$i18n.locale
			}
		},
		methods: {
			deleteClass(item) {
				this.$refs.udb.remove(item._id)
			},
			addNum(item) {
				console.log(item)
				if (item.num >= item.count) {
					uni.showToast({
						title: "不好意思库存不够了~",
						icon: 'none'
					})
					return
				}
				item.num += 1
				// 调用接口/或者云函数方式入库
			},
			deleteNum(item) {
				if (item.num === 1) {
					uni.showToast({
						title: "至少有一个商品哦~",
						icon: 'none'
					})
					return
				}
				item.num -= 1
				// 调用接口/或者云函数方式入库
			},
			//新增课程
			async addClass() {
				let res = await uniCloud.callFunction({
					name: "addclass",
					data: {
						"price": Math.floor(Math.random() * 120),
						"isPayed": false,
						"label": "Vue" + Math.floor(Math.random() * 120),
						"title": "Vue测试课程" + Math.floor(Math.random() * 120),
						"description": "Vue课程的描述哦" + Math.floor(Math.random() * 120),
						"count": 10,
						"num": 0,
						"teachers": [{
							"id": 123,
							"userIcon": "https://gitee.com/static/errors/images/logo.svg?t=158106664",
							"userName": "刘德华",
							"role": "主讲"
						}]
					}
				})
				console.log(res)
				if (res.result.code === 200) {
					this.getClassList()
				}

			},
			//语言切换
			changeLanguage() {
				console.log('changeLanguage')
				let curLang = uni.getStorageSync('language_key') || 'ZH'
				console.log(curLang)
				let nextLang = curLang === 'ZH' ? 'EN' : 'ZH'
				console.log(nextLang)
				uni.setStorageSync('language_key', nextLang)
				this.$i18n.locale = nextLang
			},
			//跳转详情页
			goDetail(item) {
				uni.navigateTo({
					url: `/pages/detail/detail?id=${item._id}`,
					success(res) {
						console.log(res)
						res.eventChannel.emit('acceptDataFromOpenerPage', item)
					}
				})
			},
			//报名
			doSumit: throttle(
				function() {
					if (!this.canSubmit) {
						uni.showToast({
							title: '请至少选择一个课程进行购买'
						})
						return
					}
					const openid = uni.getStorageSync('openid')
					//调用一个接口，在咱们业务服务端生成一个订单
					// uni.request({
					// 	url: "http://localhost:3000/order/pay",
					// 	method: "POST",
					// 	data: {
					// 		openid,
					// 		description: '测试支付'
					// 	},
					// 	success(result) {
					// 		console.log(result)
					//     	uni.requestPayMent()
					// 	}
					// })
					/** 使用unipay
					 * 
					 */
					// this.order_no = `test` + Date.now(); // 模拟生成订单号
					// this.out_trade_no = `${this.order_no}-1`; // 模拟生成插件支付单号
					// // 打开支付收银台
					// this.$refs.pay.open({
					// 	total_fee: this.total_fee, // 支付金额，单位分 100 = 1元
					// 	order_no: this.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
					// 	out_trade_no: this.out_trade_no, // 插件支付单号
					// 	description: this.description, // 支付描述
					// 	type: this.type, // 支付回调类型
					// 	custom: this.custom, // 自定义数据
					// });
					/**
					 * 使用云函数
					 */
					uni.request({
						url:'https://fc-mp-a2b27382-6a7c-4e2d-910d-dda497777459.next.bspapp.com/payOrder',
						method:"POST",
						data:{
							openid,
							id: '1231231231',
							price: '1'
						},
						success(res) {
							console.log(res)
							uni.requestPayment({ // 调用支付api
								provider: 'weixin',
								...res.data.data,
								success() {
									uni.showModal({
										title: '支付成功',
										content: '请和顾问联系执行订单即可!'
									})
								},
								fail() {}
							})
						}
					})
					// uniCloud.callFunction({
					// 	name: 'payOrder',
					// 	data: {
					// 		openid,
					// 		id: '1231231231',
					// 		price: 1
					// 	},
					// 	success(res) {
					// 		console.log(res)
					// 		uni.requestPayment({ // 调用支付api
					// 			provider: 'weixin',
					// 			...res.result.data,
					// 			success() {
					// 				uni.showModal({
					// 					title: '支付成功',
					// 					content: '请和顾问联系执行订单即可!'
					// 				})
					// 			},
					// 			fail() {}
					// 		})
					// 	}
					// })
				},
				1000
			),
			// doSumitDebounce:  debounce(this.doSubmit, 1000),
			//获取课程数据
			async getClassList() {
				// uni.request({
				// 	url:"http://localhost/mock/goods/list",
				// 	method:"GET",
				// 	success: (res) => {
				// 		console.log(res)
				// 		// #ifdef H5
				// 		this.classList = res.data.data
				// 		// #endif
				// 		// #ifdef MP-WEIXIN
				// 		this.classList = res.data
				// 		// #endif
				// 	}
				// })
				let res = await uniCloud.callFunction({
					name: "getclass",
					data: {
						pageNum: 1,
						pageSize: 10
					}
				})
				console.log(res.result)
				this.classList = res.result.data.map(item => ({
					...item,
					isSelected: false
				}))
			},
			selectAll() {
				let isAllSelect = this.classList.some(item => !item.isSelected)
				if (isAllSelect) {
					this.classList.map(item => item.isSelected = true)
				} else {
					this.classList.map(item => item.isSelected = false)
				}
			},
			selectNo() {
				this.classList.map(item => item.isSelected = !item.isSelected)
			},
			//获取优惠金额
			getPreferentialNum() {
				setTimeout(() => {
					this.preferentialNum = 100
				}, 1000)
			},
			onPullDownRefresh() {
				uni.showToast({
					title: '我要开始加载了'
				})
				this.getClassList()
			},
			doSelect(item) {
				console.log(item)
				if (!item.isPayed) {
					item.isSelected = !item.isSelected
				}

			}
		}
	}
</script>

<style lang="scss">
	.label-list {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.label-item {
			background: #ccc;
			border-radius: 10rpx;
			padding: 0 10rpx;
			margin-right: 20rpx;
		}

		&.out-label {
			position: fixed;
			//#ifdef H5
			top: 44px;
			//#endif
			//#ifdef MP-WEIXIN
			top: 88px;
			//#endif
			z-index: 999;
			padding: 25rpx 30rpx 20rpx;
			background: #fff;
			width: 100%;
		}
	}

	.content {
		padding: 30rpx 30rpx 80rpx;

		.swiper-wrap {
			width: 690rpx;
			height: 400rpx;
			margin-bottom: 25rpx;

			.swiper-image {
				// height: ;
				width: 690rpx;
				height: 400rpx;
				border-radius: 10rpx;
				margin-bottom: 25rpx;
			}
		}

		.class-list {
			.class-item {
				background: #FFF;
				border-radius: 10rpx;
				margin-bottom: 30rpx;
				padding: 20rpx;
				position: relative;

				.class-con {
					border-bottom: 1px solid #ccc;
					display: flex;
					align-items: center;
					padding-bottom: 20rpx;

					.is-select {
						margin-right: 16rpx;
						width: 50rpx;
					}

					.class-main {
						.title-row {
							display: flex;

							.class-label {
								background: #999;
								border-radius: 8rpx;
								color: #FFF;
								padding: 0 8rpx;
								margin-right: 10rpx;
							}

							.class-title {
								font-weight: bold;
							}
						}

						.classs-description {
							color: #aaa;
							margin: 10rpx 0;
						}

						.teacher-list {
							display: flex;

							.teacher-item {
								display: flex;
								align-items: center;

								.teacher-icon {
									width: 100rpx;
									height: 100rpx;
									border-radius: 50%;
									background-color: #ccc;
								}

								.teacher-info {
									display: flex;
									flex-direction: column;
									justify-content: space-between;
									height: 100rpx;

									.teacher-name {
										color: #000
									}

									.teacher-role {
										color: #bbb;
									}
								}

							}
						}
					}
				}

				.class-info {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.play-btn {
						display: flex;
						align-items: center;
					}
				}

				.class-price {
					margin-top: 30rpx;
					text-align: right;
					color: #666;
				}

				.is-payed {
					position: absolute;
					background: rgba(0, 0, 0, .2);
					width: 100rpx;
					height: 100rpx;
					bottom: 50rpx;
					right: 50rpx;
				}
			}
		}
	}

	.do-assign {
		position: fixed;
		background: #FFF;
		//#ifdef MP-WEIXIN
		bottom: 0rpx;
		//#endif
		//#ifdef H5
		bottom: 92rpx;
		//#endif
		width: 100%;
		height: 100rpx;
		padding: 30rpx;
		display: flex;
		box-sizing: border-box;
		align-items: center;
		justify-content: space-between;

		.price-num {
			color: #FD7135;
			display: flex;
			align-items: center;

			.sub-price {
				font-weight: bold;
				font-size: 52rpx;
				margin-right: 30rpx;
			}

			.preferential {
				font-size: 40rpx;
				border: 1rpx solid #FD7135;
				border-radius: 10rpx;
				padding: 0 10rpx;
			}
		}

		.disabled {
			width: 200rpx;
			height: 80rpx;
			border-radius: 40rpx;
			line-height: 80rpx;
			background: #CCC;
			color: #fff;
			text-align: center;
		}

		.submit-btn {
			width: 200rpx;
			height: 80rpx;
			border-radius: 40rpx;
			line-height: 80rpx;
			background: #FD7135;
			color: #fff;
			text-align: center;
		}
	}
</style>